<?php

namespace app\common\model\meet\product;

use think\Model;
use traits\model\SoftDelete;

class Product extends Model
{

    use SoftDelete;


    // 表名
    protected $name = 'meet_product';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [];

    const STATUS_HIDDEN = 'hidden';

    const STATUS_NORMAL = 'normal';

    /**
     * 关联商品规格表
     */
    public function spec()
    {
        return $this->hasMany('Spec','product_id','id');
    }

    /**
     * 关联商品规格关系表
     */
    public function specRel()
    {
        return $this->belongsToMany('app\\common\\model\\meet\\SpecValue', 'meet_product_spec_rel','spec_value_id','product_id');
    }

//    public function getCoverImageAttr($value)
//    {
//        return $value ? cdnurl($value, true) : '';
//    }
//
//    public function getImagesAttr($value)
//    {
//        $list = [];
//        if ($value) {
//            $list = explode(',', $value);
//
//            foreach ($list as $k => $v) {
//                $list[$k] = cdnurl($v, true);
//            }
//        }
//        return $list;
//    }

    /**
     * 获取规格信息
     */
    public function getManySpecData($spec_rel, $skuData)
    {
        // spec_attr
        $specAttrData = [];
        foreach ($spec_rel as $item) {
            if (!isset($specAttrData[$item['spec_id']])) {
                $specAttrData[$item['spec_id']] = [
                    'group_id' => $item['spec']['id'],
                    'group_name' => $item['spec']['spec_name'],
                    'spec_items' => [],
                ];
            }
            $specAttrData[$item['spec_id']]['spec_items'][] = [
                'item_id' => $item['pivot']['spec_value_id'],
                'spec_value' => $item['spec_value'],
            ];
        }

        // spec_list
        $specListData = [];
        foreach ($skuData as $item) {
            $specListData[] = [
                'product_spec_id' => $item['spec_id'],
                'spec_sku_id' => (string)$item['spec_sku_id'],
                'rows' => [],
                'form' => [
                    'product_price' => $item['product_price'],
                    'product_deposit' => $item['product_deposit'],
                    'product_people_nums' => $item['product_people_nums'],
                    'spec_status' => $item['spec_status'],
                    'spec_image' => $item['spec_image'],
                ],
            ];
        }
        return ['spec_attr' => array_values($specAttrData), 'spec_list' => $specListData];
    }
}
